package com.dhcy.mqtt.controller;


import com.dhcy.mqtt.model.SysResource;
import com.dhcy.mqtt.model.SysResourceMenu;
import com.dhcy.mqtt.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/")
    public  String index(Model model){
    	//log.error(System.currentTimeMillis()+"");
        String username=(String)SecurityUtils.getSubject().getPrincipal();
        //JWTUtil.getUsername((String)SecurityUtils.getSubject().getPrincipal());
        List<SysResource> resourceListByusername =  sysUserService.getResourceListByusername(username);
        model.addAttribute("titles",conllectMenu(resourceListByusername));
        //log.error(System.currentTimeMillis()+"执行完了");

        return "index";
    }


    private  List<SysResourceMenu> conllectMenu(List<SysResource> resourceListByusername){
        Map<Integer,SysResourceMenu> map=new LinkedHashMap<>();
       List<SysResourceMenu> sysResourceMenuList=new ArrayList<>();
       SysResourceMenu sysResourceMenu=new SysResourceMenu();
       for (SysResource sysResource:resourceListByusername){
           if(sysResource.getParentId()==null){
               sysResourceMenu=new SysResourceMenu();
               sysResourceMenu.setSysResourceList(new ArrayList<>());
               BeanUtils.copyProperties(sysResource,sysResourceMenu);
               map.put(sysResource.getId(),sysResourceMenu);
           }else {
               SysResourceMenu sysResourceMenu1=map.get(sysResource.getParentId());
               if(sysResourceMenu1!=null){
               List<SysResource> sysResourceList=sysResourceMenu1.getSysResourceList();
               sysResourceList.add(sysResource);
               sysResourceMenu1.setSysResourceList(sysResourceList);
               }
           }
       }
       for (Integer key:map.keySet()){
           sysResourceMenuList.add(map.get(key));
       }
       return  sysResourceMenuList;
    }
}
